package com.sentiment.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bson.types.ObjectId;
import org.json.JSONObject;

import com.sentiment.database.bean.DailyReport;
import com.sentiment.database.bean.HotspotReport;
import com.sentiment.report.DailyReportUtils;
import com.sentiment.report.HotReportUtils;

/**
 * Servlet implementation class HotSentimentServlet
 */
@WebServlet("/HotSentimentServlet")
public class HotSentimentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private DailyReportUtils dailyUtils = new DailyReportUtils();
	private HotReportUtils reportUtils = new HotReportUtils();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public HotSentimentServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		String methodName = request.getParameter("method");
		try {
			Method method = getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	/**
	 * 将今日已发布的每日舆情报告 转为未监测的热点舆情报告
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void createHotspotReport(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<DailyReport> list = dailyUtils.findDailyReport(new Date(), true);
		for (DailyReport report : list) {
			reportUtils.watchHotReport(report.get_id());
		}
	}

	/**
	 * 获取到所有未监测完成的热点舆情报告（后端方法）
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void getHotspotReports(HttpServletRequest request, HttpServletResponse response) throws IOException {

		List<HotspotReport> list = reportUtils.findHotspotReport(HotReportUtils.UN_WATCHED);

		StringBuilder sbd = new StringBuilder();
		if (list != null && !list.isEmpty()) {
			sbd.append("{\"reports\":[");
			for (HotspotReport report : list) {
				sbd.append(report.toJson() + ",");

			}
			sbd.deleteCharAt(sbd.length() - 1);
			sbd.append("]}");
		}

		response.setCharacterEncoding("utf-8");
		response.getWriter().print(sbd.toString());
	}

	/**
	 * 获取和改变发布状态（后端方法）
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void changeReportStatus(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		Integer status = reportUtils.updateStatus(new ObjectId(id));

		response.setCharacterEncoding("utf-8");
		response.getWriter().print(status + "");
	}

	/**
	 * 执行一次监测（
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */

	public void doWatch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		reportUtils.watchExecute();
	}

	/**
	 * 根据id获取一篇热点舆情报告（通用方法）
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void getHotspotReportById(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id");

		HotspotReport report = reportUtils.findHotspotReport(new ObjectId(id));

		List<JSONObject> commentRatio = toJSONList(report.getCommentRatio());
		List<JSONObject> sentimentRatio = toJSONList(report.getSentimentRatio());
		List<JSONObject> reprintRatio = toJSONList(report.getReprintRatio());
		StringBuilder sbd = new StringBuilder();
		
		sbd.append(report.toJson());
		sbd.deleteCharAt(sbd.length()-1);
		sbd.append(",\"commentGraph\":" + commentRatio);
		sbd.append(",\"sentimentGraph\":" + sentimentRatio);
		sbd.append(",\"reprintGraph\":" + reprintRatio);
		sbd.append("}");
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(sbd.toString());
	}

	/**
	 * 按页获取所有已发布的热点舆情报告（前端方法）
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void getPublishedReportPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int pagenum = Integer.parseInt(request.getParameter("pagenum"))-1;
		List<HotspotReport> reports = reportUtils.findHotspotReport(HotReportUtils.PUBLISHED);
		List<HotspotReport> result = new ArrayList<HotspotReport>();
		for(int i = pagenum * 10 ; i < (pagenum+1) * 10 ;  i++){
			if(i < reports.size())
				result.add(reports.get(i));
		}
		
		StringBuilder sbd = new StringBuilder();
		if (reports != null && !reports.isEmpty()) {
			sbd.append("{\"reports\":[");
			for (HotspotReport report : reports) {
				List<JSONObject> commentRatio = toJSONList(report.getCommentRatio());
				List<JSONObject> sentimentRatio = toJSONList(report.getSentimentRatio());
				List<JSONObject> reprintRatio = toJSONList(report.getReprintRatio());
				
				sbd.append(report.toJson());
				sbd.deleteCharAt(sbd.length()-1);
				sbd.append(",\"commentGraph\":" + commentRatio);
				sbd.append(",\"sentimentGraph\":" + sentimentRatio);
				sbd.append(",\"reprintGraph\":" + reprintRatio);
				sbd.append("},");
			}
			sbd.deleteCharAt(sbd.length() - 1);
			sbd.append("]}");
		}
		response.setCharacterEncoding("utf-8");
		response.getWriter().print(sbd.toString());
	}
	private List<JSONObject> toJSONList(Map<String, ? extends Object> map){
		List<JSONObject> list = new ArrayList<JSONObject>();
		for(Entry<String, ? extends Object> entry : map.entrySet()){
			JSONObject json = new JSONObject();
			json.put("val", entry.getValue());
			json.put("key", entry.getKey());
			list.add(json);
		}
		return list;
	}
	/**
	 * 按页获取所有热点舆情报告（后端方法）
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void getHotspotReportPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 传入页码
		Integer pagenum = Integer.parseInt(request.getParameter("pagenum"));

		List<HotspotReport> reports = reportUtils.findHotspotReport(pagenum, 10);
		StringBuilder sbd = new StringBuilder();

		if (reports != null && !reports.isEmpty()) {
			sbd.append("{\"reports\":[");
			for (HotspotReport report : reports) {
				sbd.append(report.toJson() + ",");
			}
			sbd.deleteCharAt(sbd.length() - 1);
			sbd.append("]}");
		}

		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(sbd.toString());
	}

}
